﻿using Sprout.Core;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace Sprout.Schedule.Web.Utils
{
    public class SessionHelper
    {
        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Write(string key, string value)
        {
            IHttpContextAccessor hca = ServiceLocator.GetService<IHttpContextAccessor>();
            hca?.HttpContext?.Session.Set(key, Encoding.UTF8.GetBytes(value));
        }

        /// <summary>
        /// 读session值
        /// </summary>
        /// <param name="key">名称</param>
        /// <returns>值</returns>
        public static string Get(string key)
        {
            IHttpContextAccessor hca = ServiceLocator.GetService<IHttpContextAccessor>();
            if (hca == null || hca.HttpContext == null)
            {
                return string.Empty;
            }
            byte[] temp;
            if (hca.HttpContext.Session.TryGetValue(key, out temp))
            {
                return Encoding.UTF8.GetString(temp);
            }
            return string.Empty;

        }

        /// <summary>
        /// 删除Session对象
        /// </summary>
        /// <param name="key">key</param>
        public static void Remove(string key)
        {
            IHttpContextAccessor hca = ServiceLocator.GetService<IHttpContextAccessor>();
            hca?.HttpContext?.Session.Remove(key);
        }
    }
}
